//
//  PageBuildModel.swift
//  
//
//  Created by 孙长坦 on 2022/7/7.
//

import Foundation

public struct BuildModel {
    public let host: String?
    
    public let moduleType: String
    
    public let moduleId: String?
    
    public let type: String?
    
    public let id: String?
    
    public var params: [String: Any]?
    
    public let hash: String?
    
    public init?(url: String, params: [String: Any]?) {
        guard let urlComponents = URLComponents.ex.create(string: url) else {
            return nil
        }
        
        self.init(urlComponents: urlComponents, params: params)
    }
    
    public init?(urlComponents: URLComponents, params: [String: Any]?) {
        let paths = urlComponents.path.split(separator: "/")
        guard paths.count > 0 else {
            return nil
        }
        
        host = urlComponents.host
        
        self.params = Dictionary.merging(value1: urlComponents.ex.getQueryItems(),
                                         value2: params)
        
        moduleType = String(paths[0])
        type = paths.count == 1 ? nil : String(paths[1])
        
        if paths.count > 2 {
            let pathParams = [paths.suffix(from: 2).map { String($0) }]
            self.params = Dictionary.merging(value1: self.params, value2: ["pathParams": pathParams])
        }
        
        if let params = self.params {
            moduleId = params["moduleId"] as? String
            id = (params["pageId"] ?? params["handlerId"] ?? params["id"]) as? String
        } else {
            moduleId = nil
            id = nil
        }
        
        hash =  urlComponents.fragment
    }
    
    public static func url(moduleType: String, moduleId: String?,
                           pageType: String, pageId: String?) -> String {
        var url = "app://page/\(moduleType)/\(pageType)"
        
        var params: String = "";
        if let moduleId = moduleId {
            params += "moduleId=\(moduleId)"
        }
        
        if let pageId = pageId {
            if params.count > 0 {
                params += "&"
            }
            params += "pageId=\(pageId)"
        }
        
        if params.count > 0 {
            url += "?" + params
        }
        
        return url
    }
}
